package com.cloudmusic.controller;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONObject;
import com.cloudmusic.constant.Const;
import com.cloudmusic.entity.User;
import com.cloudmusic.service.UserService;
import com.cloudmusic.utils.MD5Util;

@Controller
@RequestMapping("music/user")
public class UserController {

    @Autowired
    private UserService userService;

    private Logger log=Logger.getLogger(this.getClass());

    //判断是否登录
    @RequestMapping("isLogIn")
    @ResponseBody
    public JSONObject isLogIn(HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        if(session.getAttribute(Const.SESSION_KEY) != null) {
            jsonObject.put("isLogin", true);
            jsonObject.put("userName", ((User)(session.getAttribute(Const.SESSION_KEY))).getUsername());
            String uid =  ((User)(session.getAttribute(Const.SESSION_KEY))).getUid();
            List list = userService.selectUserInfo(uid);
            jsonObject.put("rows", list);
        }else {
            jsonObject.put("isLogin", false);
        }
        return jsonObject;
    }

    //登录功能
    @RequestMapping("logIn")
    @ResponseBody
    public JSONObject logIn(User user,HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        int result = 0;
        if (user.getUsername().isEmpty() || user.getPassword().isEmpty()) {
            jsonObject.put("logInJudge", "false");
            jsonObject.put("logInTip", "请输入用户名或密码");
        } else {
            List<User> users = userService.getUsersList(user.getUsername());
            //检验查找的用户信息不为空且不处于禁用状态
            if (users.size()!=0 && users.get(0).getIsenabled() != 0) {
                if (MD5Util.getStringMD5(user.getPassword()).equals(users.get(0).getPassword())) {
                    result = 1;
                    session.setAttribute(Const.SESSION_KEY,users.get(0));
                    //获取用户历史歌单id存入session
                    String userhistorylid = userService.selectUserHistoryListId(users.get(0).getUid());
                    session.setAttribute(Const.HISTORYLIST_ID,userhistorylid);
                    jsonObject.put("logInJudge", true);
                    jsonObject.put("logInTip", result);
                    jsonObject.put("userNameCurrent", users.get(0).getUsername());
                    //获取用户个人信息
                    List list = userService.selectUserInfo(users.get(0).getUid());
                    jsonObject.put("rows", list);
                } else {
                    result = 2;
                    jsonObject.put("logInTip", result);
                }
            } else {
                result = 0;
                jsonObject.put("logInTip", result);
            }
        }
        return jsonObject;
    }

    //注册
    @RequestMapping("signIn")
    @ResponseBody
    public JSONObject signIn(@RequestParam(value = "signInUserName") String signInUserName,
                             @RequestParam(value = "signInPassWord1") String password1, @RequestParam(value = "signInPassWord2") String password2,HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        if((signInUserName.trim()).isEmpty()||password1.isEmpty()||password2.isEmpty()) {
            jsonObject.put("signInJudge","false");
            jsonObject.put("signInTip","请完善个人信息");
        }else {
            if (password1.equals(password2)) {
                String isExit = userService.isExitUserName(signInUserName);
                if (isExit!=null) {
                    jsonObject.put("signInTip","用户名已被占用");
                }else {
                    User newuser = new User();
                    newuser.setUsername(signInUserName.trim());
                    newuser.setPassword(MD5Util.getStringMD5(password1));
                    String uid = UUID.randomUUID().toString();
                    String likelid = UUID.randomUUID().toString();
                    String collectionlid = UUID.randomUUID().toString();
                    String historylid = UUID.randomUUID().toString();
                    try {
                        userService.userSignIn(newuser,uid,likelid,collectionlid,historylid);
                        jsonObject.put("signInJudge",true);
                        jsonObject.put("signInTip","注册成功");
                        log.info("注册成功");
                    } catch (Exception e) {
                        jsonObject.put("signInTip","注册失败");
                        log.error("注册失败",e);
                    }
                }
            }else {
                jsonObject.put("signInTip","两次输入的密码不一致");
            }
        }

        return jsonObject;
    }

    //退出
    @RequestMapping("signOut")
    @ResponseBody
    public JSONObject signIn(HttpSession session) {
        JSONObject jsonObject = new JSONObject();
        try {
            if (Const.SESSION_KEY!=null) {
                session.removeAttribute(Const.SESSION_KEY);
                session.removeAttribute(Const.HISTORYLIST_ID);
                jsonObject.put("signOutJudge","true");
            }
        } catch (Exception e) {
            log.error("退出有异常");
            jsonObject.put("signOutJudge","false");
        }
        return jsonObject;
    }

    //找出某用户的自定义歌单，可能null
    @RequestMapping("findsonglists")
    @ResponseBody
    public JSONObject findSongLists(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        try {
            String userId = ((User)request.getSession().getAttribute(Const.SESSION_KEY)).getUid();
            List<Map<String,Object>> songList = userService.findSongLists(userId);
            jsonObject.put("songList", songList);
        } catch (Exception e) {
            log.error("查找出错",e);
        }
        return jsonObject;
    }

    //播放音乐时更新音乐的最后播放时间状态
    @RequestMapping("playmusic")
    @ResponseBody
    public JSONObject playmusic(HttpServletRequest request){
        JSONObject json = new JSONObject();
        String sid = request.getParameter("songid");
        try{
            String historylid = (String) request.getSession().getAttribute(Const.HISTORYLIST_ID);
            userService.playMusic(historylid,sid);
            log.info("更新音乐播放时间成功");
            json.put("result","success");
        }catch (Exception e){
            log.info("更新音乐播放时间出错",e);
            json.put("result","false");
        }
        return json;
    }

    //更新用户个人信息
    @RequestMapping("updateuserinfo")
    @ResponseBody
    public JSONObject updateuserinfo(HttpServletRequest request,String nname,String sex ,String phone ,String email){
        int result = 0;
        JSONObject json = new JSONObject();
        String userId = ((User)request.getSession().getAttribute(Const.SESSION_KEY)).getUid();
        try{
            userService.updateUserInfo(nname,sex,phone,email,userId);
            result = 1;
            json.put("result",result);
            log.info("成功修改用户个人信息");
        }catch (Exception e){
            result = 2;
            json.put("result",result);
            log.error(e);
        }
        return json;
    }

    //注销用户
    @RequestMapping("banuser")
    @ResponseBody
    public JSONObject banUser(HttpServletRequest request){
        JSONObject json = new JSONObject();
        String userId = ((User)request.getSession().getAttribute(Const.SESSION_KEY)).getUid();
        int result = userService.banUser(userId);
        if(result == 1){
            log.info(userId+"用户注销成功");
        }else if(result == 0){
            log.info(userId+"用户注销失败");
        }
        json.put("result",result);
        return json;
    }

    //修改用户密码
    @RequestMapping("changepassword")
    @ResponseBody
    public JSONObject changeUserPassword(HttpServletRequest request,String oldpassword,String newpassword){
        JSONObject json = new JSONObject();
        String userId = ((User)request.getSession().getAttribute(Const.SESSION_KEY)).getUid();
        int result = userService.changeUserPassword(userId,MD5Util.getStringMD5(oldpassword),MD5Util.getStringMD5(newpassword));
        json.put("result",result);
        return json;
    }


}
